package cn.maihe.elg.operation.utils;

import cn.maihe.elg.operation.model.dto.BaseReq;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import io.jsonwebtoken.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.junit.Test;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author WJH
 * @Date 2021/09/23
 */
@Slf4j
public class PdfFillUtil {

    public static Path fillPdf(Path templatePath, Path targetPath, BaseReq paramsObj) {
        try {
            Map<String, String> params = BeanUtilsBean.getInstance().describe(paramsObj);
            return fillPdfByMap(templatePath, targetPath, params);
        } catch (Exception e) {
            log.error("填充pdf模板异常：{}", e.getMessage(), e);
            throw new RuntimeException(e);
        }

    }

    public static Path fillPdfByMap(Path templatePath, Path targetPath, Map<String, String> params) {
        Assert.notNull(templatePath, "templatePath不能为空");
        Assert.notNull(targetPath, "targetPath不能为空");
        Assert.isTrue(Files.exists(templatePath), "模板文件不存在");
        PdfStamper ps = null;
        PdfReader reader = null;
        try (InputStream inputStream = Files.newInputStream(templatePath);) {
            reader = new PdfReader(inputStream);
            ps = new PdfStamper(reader, new FileOutputStream(targetPath.toFile()));

            AcroFields form = ps.getAcroFields();
            BaseFont bf = BaseFont.createFont("/simsun.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            form.addSubstitutionFont(bf);

            if (params != null && !params.isEmpty()) {
                for (String key : params.keySet()) {
                    form.setField(key, params.get(key).toString());
                }
            }

            ps.setFormFlattening(true);

            log.info("pdf填充完成. {} >> {}", templatePath.toFile().getName(), targetPath.toFile().getName());
        } catch (Exception e) {
            log.error("pdf填充失败. {} >> {}", templatePath.toFile().getName(), targetPath.toFile().getName(), e);
            throw new RuntimeException("pdf填充失败", e);
        } finally {
            try {
                if (ps != null) {
                    ps.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                log.error("关闭ps|reader异常：", e.getMessage(), e);
            }
        }
        return targetPath;
    }


    @Test
    public void guaranteePdf() {
// resource/template/存在已调整过的模板pdf
        Path templatePath = Paths.get("d:/tm/担保保函模板.pdf");
        Path targetPath = Paths.get("d:/tm/担保保函.pdf");

        Map<String, String> data = new HashMap();
        data.put("guaranteeNo", "C00041442676701455");
        data.put("tenderName", "深圳市万川信息科技股份有限公司（福州分公司12）技股份有限公司（福州分公司12）");
        data.put("bidderName", "福州建筑建设工程有限公司福州建筑建设工程有限公司福州建筑建设工程有限公司");
        data.put("projectName", "光泽-施工标-验证工程、保险保函-RNM1231光泽-施工标-验证工程、保险保函-RNM1231");
        data.put("bidBond", CurrencyUpperUtil.toCurrencyUpper("500000"));
        data.put("year", "2021");
        data.put("month", "09");
        data.put("day", "23");

        fillPdfByMap(templatePath, targetPath,data);

    }

    @Test
    public void receivePdf() {

        Path templatePath = Paths.get("d:/tm/到账证明模板.pdf");
        Path targetPath = Paths.get("d:/tm/到账证明.pdf");

        Map<String, String> data = new HashMap();
        data.put("guaranteeNo", "C00041442676701455");
        data.put("tenderName", "深圳市万川信息科技股份有限公司（福州分公司12）川信息科技股份有限");
        data.put("bidderName", "福州建筑建设工程有限公司川信息科技股份有限川信息科技股份有限");
        data.put("projectCode", "C4144267670767014014");
        data.put("projectName", "光泽-施工标-验证工程、保险保函-RNM1231保险保函-RNM1231川信息科");
        data.put("bidBond", "500000.00");
        data.put("year", "2021");
        data.put("month", "09");
        data.put("day", "23");

        data.put("payeeAccNo", "622909123456789");
        data.put("payerAccNo", "622909666666688");

        data.put("signYear", "2021");
        data.put("signMonth", "09");
        data.put("signDay", "23");


        fillPdfByMap(templatePath, targetPath, data);

    }

    @Test
    public void applyPdf() {

        Path templatePath = Paths.get("d:/tm/委托申请书模板.pdf");
        Path targetPath = Paths.get("d:/tm/委托申请书.pdf");

        Map<String, String> data = new HashMap();
        data.put("tenderName", "福建福州水利工程有限公司==福建福州水利工程有限公司");
        data.put("bidderName", "福州建筑建设工程有限公司===福州建筑建设工程有限公司");
        data.put("projectName", "同城县基础水利工程二期项目===同城县基础水利工程二期项目");
        data.put("year", "2021");
        data.put("month", "09");
        data.put("day", "23");

        fillPdfByMap(templatePath, targetPath, data);

    }

    @Test
    public void promisePdf() {

        Path templatePath = Paths.get("d:/tm/反担保承诺书模板.pdf");
        Path targetPath = Paths.get("d:/tm/反担保承诺书.pdf");

        Map<String, String> data = new HashMap();
        data.put("bidderName", "福州建筑建设工程有限公司");
        data.put("projectName", "同城县基础水利工程二期项目");
        data.put("year", "2021");
        data.put("month", "09");
        data.put("day", "23");

        fillPdfByMap(templatePath, targetPath, data);

    }

}
